package com.kalle.workflow.engine;

import com.kalle.workflow.service.*;
import com.kalle.workflow.service.impl.*;
import com.kalle.workflow.util.IdGenerator;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;

public class WorkflowEngineImpl implements WorkflowEngine {

    private final SqlSession sqlSession;
    private final IdGenerator idGenerator;

    WorkflowEngineImpl(DataSource dataSource, IdGenerator idGenerator) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        Configuration configuration = sqlSessionFactory.getConfiguration();
        configuration.setEnvironment(new Environment("workflow", new JdbcTransactionFactory(), dataSource));
        //sqlSession
        this.sqlSession = sqlSessionFactory.openSession();
        //id generator
        this.idGenerator = idGenerator;
    }

    @Override
    public DeploymentService getDeploymentService() {
        return new DeploymentServiceImpl(this.sqlSession, this.idGenerator);
    }

    @Override
    public TaskService getTaskService() {
        return new TaskServiceImpl(this.sqlSession);
    }

    @Override
    public SequenceFlowService getSequenceFlowService() {
        return new SequenceFlowServiceImpl(this.sqlSession);
    }

    @Override
    public ProcessService getProcessService() {
        return new ProcessServiceImpl(this.sqlSession, this.idGenerator);
    }

    @Override
    public FlowService getFlowService() {
        return new FlowServiceImpl(this.sqlSession, this.idGenerator);
    }
}
